package com.web.common.ctrl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import com.css.sword.kernel.base.exception.SwordBaseCheckedException;
import com.css.sword.kernel.utils.SwordFileUtils;
import com.css.sword.kernel.utils.SwordLogUtils;
import com.css.sword.kernel.utils.SwordServiceUtils;
import com.css.sword.platform.web.comm.WebRootUtil;
import com.css.sword.platform.web.controller.BaseDomainCtrl;
import com.css.sword.platform.web.controller.annotations.CTRL;
import com.css.sword.platform.web.event.IReqData;
import com.css.sword.platform.web.event.IResData;
import com.css.sword.platform.web.event.SwordRes;
import com.css.sword.platform.web.fileupload.intimeup.SwordFileItem;
import com.sun.org.apache.xpath.internal.XPathAPI;
import com.web.common.utils.XMLAdapter;

@CTRL("File2Ctrl")
public class File2Ctrl extends BaseDomainCtrl {

	private static SwordLogUtils log = SwordLogUtils.getLogger(File2Ctrl.class);

	@SuppressWarnings("unused")
	public IResData download(IReqData req) throws FileNotFoundException,
			SwordBaseCheckedException {
		String path = "";
		path = SwordFileUtils.getSwordRootPath();

		String filePath = WebRootUtil.getWebRootPath();
		this.downLoad(new File(filePath
				+ "/pages/sworddemo/file2test/images/test.zip"), "test.zip");
		return new SwordRes();
	}

	@SuppressWarnings({ "rawtypes" })
	public IResData deleteFile(IReqData req) throws FileNotFoundException {
		/*
		 * 此处填写真正的文件删除代码。 若删除失败请抛出异常
		 */
		log.info("进入删除文件方法！");
		IResData res = new SwordRes();
		// 获取前台传递过来的type=file2的name值
		String form = (String) req.getAttr("file2");
		// 获取文件信息
		Map file2 = req.getForm(form);
		// 获取文件路径
		String filePath = (String) file2.get("path");
		String fileId = (String) file2.get("fileId");
		String path;
		try {
			if(fileId != null && !fileId.equals("")){
				req.setBizParams("fileId", fileId);
				// 删除数据库中的附件字段
				res=(IResData) SwordServiceUtils.callService("FjService_delFjfile", req);
				// 删除服务器上的文件
				path = getFilePath(filePath);
				//path = path.replace("/", "\\");
				File deleteFile = new File(path);
				if (deleteFile.exists()) {
					deleteFile.delete();
				}
			}
		} catch (SwordBaseCheckedException e) {
			e.printStackTrace();
		}
		return res;
	}

	@SuppressWarnings("rawtypes")
	public IResData saveForm(IReqData req) throws Exception {
		IResData res = new SwordRes();
		/*
		 * 传入req,表单名字,file2类型对应的字段名返回list<swordfileitem> 列表.
		 */
		List<SwordFileItem> a = this
				.getFormUploadList2(req, "form_1", "newup0");
		Iterator b = a.iterator();
		SwordFileItem sfi = null;
		while (b.hasNext()) {
			sfi = (SwordFileItem) b.next();
			String name = sfi.getName();
			if (sfi.isNewFile()) {
				System.out.println("文件" + name + " 是新增的文件");
				// Map dataMap=sfi.getDataMap();dataMap是dataName对应list的文件信息map.
			} else {
				System.out.println("文件" + name + " 是后台通过dataName初始化的文件");
			}
		}
		return res;
	}

	@SuppressWarnings("rawtypes")
	public IResData saveGrid(IReqData req) throws Exception {
		IResData res = new SwordRes();
		/*
		 * 第一种方式.传入req,表格名字,file2类型对应的列名返回list<swordfileitem> 列表.
		 */
		List<SwordFileItem> a = this.getGridUploadFile2(req, "grid_1",
				"insert_2");
		Iterator b = a.iterator();
		SwordFileItem sfi = null;
		while (b.hasNext()) {
			sfi = (SwordFileItem) b.next();
			String name = sfi.getName();

			if (sfi.isNewFile()) {
				System.out.println("文件" + name + " 是新增的文件");
				// Map dataMap=sfi.getDataMap();dataMap是dataName对应list的文件信息map.
			} else {
				System.out.println("文件" + name + " 是后台通过dataName初始化的文件");
			}
		}
		/*
		 * 第二种方式.传入表格中某一行数据map对应的file2类型对应列值，返回swordfileitem 对象.
		 */
		sfi = this.getGridUploadFile2(req.getTable("grid_1").get(0)
				.get("insert_2"));

		return res;
	}

	// 以下两函数是在获取服务器绝对路径
	public String getFilePath(String filePath) throws SwordBaseCheckedException {
		//String rootPath = WebRootUtil.getWebRootPath();
		String uploadPath = getRootPath() + filePath;
		return uploadPath;
	}

	public String getRootPath() throws SwordBaseCheckedException {
		String path = SwordFileUtils.getSwordRootPath();
		int lastIndex = path.lastIndexOf("WEB-INF");
		String rootPath = path.substring(0, lastIndex).replace("\\", "/");
		return rootPath;
	}

	public static void main(String[] args) {
		File file = new File("file-server.xml");
		if (!file.exists()) {
			System.out.println("什么都没有！");
			return;
		}
		try {
			Document document = XMLAdapter.load(new FileInputStream(
					"file-server.xml"));
			TransformerFactory tfactory = TransformerFactory.newInstance();
			Transformer transformer = tfactory.newTransformer();
			DOMSource source = new DOMSource(document);
			StringWriter sw = new StringWriter();
			StreamResult a = new StreamResult(sw);
			transformer.transform(source, a);
			Node node = XPathAPI.selectSingleNode(document,
					"//FileDomainList/FileDomain[@Name='filetemppath']");

			System.out.println("****************************************");
			System.out.println(sw.toString());
			System.out.println(((Element) node).getAttribute("Path"));
			System.out.println("****************************************");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}